package com.tanhua.backmanage.service;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.backmanage.PageDTO;
import com.tanhua.backmanage.vo.Movements;
import com.tanhua.backmanage.vo.PageResult;
import com.tanhua.common.pojo.Totals;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.dubbo.server.api.MessagesApi;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.pojo.Publish;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class MessagesService {
    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Reference(version = "1.0.0")
    private MessagesApi messagesApi;

    @Autowired
    private UserInfoService1 userInfoService;

    /**
     * 消息列表
     *
     * @param param
     * @return
     */
    public PageResult messagesList(PageDTO param) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(param.getPage());
        pageResult.setPagesize(param.getPagesize());

        List<Publish> publishList = this.messagesApi.queryPublishList(param.getUid(), param.getEd(), param.getSd());

        //模糊查询
        if (!StringUtils.isEmpty(param.getId())) {
            publishList = publishList.stream().filter(s -> s.getUserId().toString().contains(param.getId())).collect(Collectors.toList());
        }

        Long i = publishList.stream().filter(s -> "3".equals(s.getState())).count(); //待审核数
        Long ii = publishList.stream().filter(s -> "4".equals(s.getState())).count(); //未通过数
        Long iii = publishList.stream().filter(s -> "5".equals(s.getState())).count(); //已通过数
        Totals totals1 = new Totals("全部", "all", publishList.size());
        Totals totals2 = new Totals("待审核", "3", i.intValue());
        Totals totals3 = new Totals("已通过", "5", iii.intValue());
        Totals totals4 = new Totals("已驳回", "4", ii.intValue());
        List<Totals> totalsList = new ArrayList<>();
        totalsList.add(totals1);
        totalsList.add(totals2);
        totalsList.add(totals3);
        totalsList.add(totals4);
        pageResult.setTotals(totalsList);

        //筛选审核类型
        if (null != param.getState() && !"all".equals(param.getState())) {
            publishList = publishList.stream().filter(s -> param.getState().equals(s.getState())).collect(Collectors.toList());
        }

        if (CollectionUtils.isEmpty(publishList)) {
            pageResult.setCounts(0);
            pageResult.setPages(0);
            return pageResult;
        }

        //获得用户id
        Set<Long> ids = publishList.stream().map(Publish::getUserId).collect(Collectors.toSet());
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.in("user_id", ids);
        List<UserInfo> userInfos = this.userInfoService.queryUserInfoList(wrapper);

        //获得查询出的详细信息
        List<Movements> movementsList = new ArrayList<>();
        for (Publish publish : publishList) {
            Long likeCount = this.quanZiApi.queryCommentCount(publish.getId().toHexString());//点赞数
            Long commentCount = this.quanZiApi.queryCommentCount(publish.getId().toHexString());//点赞数

            Movements movements = new Movements();

            for (UserInfo userInfo : userInfos) {
                if (publish.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    movements.setNickname(userInfo.getNickName());
                    movements.setUserLogo(userInfo.getLogo());
                    break;
                }
            }

            movements.setId(publish.getId().toHexString());
            movements.setUserId(publish.getUserId());
            movements.setCreateDate(publish.getCreated());
            movements.setText(publish.getText());
            movements.setMedias(publish.getMedias().toArray(new String[publish.getMedias().size()]));
            movements.setState(publish.getState());
            movements.setTopState(publish.getTopState());
            movements.setCommentCount(commentCount.intValue());
            movements.setLikeCount(likeCount.intValue());

            movementsList.add(movements);
        }

//        //排序
//        if (param.getUid() != null) {
//            Collections.sort(movementsList, (o1, o2) -> {
//                int x = o2.getTopState() - o1.getTopState();
//                int y = 0;
//                switch (param.getSortProp()) {
//                    case "reportCount": {
//                        y = o1.getReportCount() - o2.getReportCount();
//                        break;
//                    }
//                    case "likeCount": {
//                        y = o1.getLikeCount() - o2.getLikeCount();
//                        break;
//                    }
//                    case "commentCount": {
//                        y = o1.getCommentCount() - o2.getCommentCount();
//                        break;
//                    }
//                    case "forwardingCount": {
//                        y = o1.getForwardingCount() - o2.getForwardingCount();
//                        break;
//                    }
//                    case "createDate": {
//                    }
//                    default: {
//                        y = (int) (o1.getCreateDate() - o2.getCreateDate());
//                        break;
//                    }
//                }
//                if ("descending".equals(param.getSortOrder())) {
//                    y = -y;
//                }
//                return x == 0 ? y : x;
//            });
//        } else {
//            Collections.sort(movementsList, (o1, o2) -> {
//                return (int) (o1.getCreateDate() - o2.getCreateDate());
//            });
//        }

        //分页
        Integer page = Math.max(1, param.getPage() == null ? 1 : param.getPage());
        Integer pageSize = Math.max(1, param.getPagesize() == null ? 1 : param.getPagesize());
        List<Movements> newMovements = new ArrayList<>();
        int startIndex = (page - 1) * pageSize;
        if (startIndex < movementsList.size()) {
            int endIndex = startIndex + pageSize - 1;
            if (endIndex >= movementsList.size()) {
                endIndex = movementsList.size() - 1;
            }

            newMovements = movementsList.subList(startIndex, endIndex + 1);
        }

        pageResult.setCounts(movementsList.size());
        pageResult.setPages((int) Math.ceil(movementsList.size() / pageSize));
        pageResult.setItems(newMovements);


        return pageResult;
    }

    /**
     * 消息通过
     *
     * @param publishIds
     * @return
     */
    public String messagesPass(List<String> publishIds) {
        if (CollectionUtils.isEmpty(publishIds)) {
            return null;
        }
        return this.messagesApi.messagesRevocation(publishIds, "5") ? "操作成功" : null;
    }

    /**
     * 消息拒绝(批量)
     *
     * @param publishIds
     * @return
     */
    public String messagesReject(List<String> publishIds) {
        if (CollectionUtils.isEmpty(publishIds)) {
            return null;
        }
        return this.messagesApi.messagesRevocation(publishIds, "4") ? "操作成功" : null;
    }

    /**
     * 消息撤销(批量)
     *
     * @param publishIds
     * @return
     */
    public String messagesRevocation(List<String> publishIds) {
        if (CollectionUtils.isEmpty(publishIds)) {
            return null;
        }
        return this.messagesApi.messagesRevocation(publishIds, "3") ? "操作成功" : null;
    }

    /**
     * 消息详情
     *
     * @param publishId
     * @return
     */
    public Movements messagesDetails(String publishId) {
        Publish publish = this.quanZiApi.queryPublishById(publishId);
        if (publish == null) {
            return null;
        }
        Long likeCount = this.quanZiApi.queryCommentCount(publishId);//点赞数
        Long commentCount = this.quanZiApi.queryCommentCount(publishId);//评论数

        Movements movements = new Movements();

        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(publish.getUserId());
        if (null != userInfo) {
            movements.setNickname(userInfo.getNickName());
            movements.setUserLogo(userInfo.getLogo());
        }

        movements.setId(publishId);
        movements.setUserId(publish.getUserId());
        movements.setCreateDate(publish.getCreated());
        movements.setText(publish.getText());
        movements.setMedias(publish.getMedias().toArray(new String[publish.getMedias().size()]));
        movements.setState(publish.getState());
        movements.setTopState(publish.getTopState());
        movements.setCommentCount(commentCount.intValue());
        movements.setLikeCount(likeCount.intValue());

        return movements;
    }

    /**
     * 消息置顶
     *
     * @param publishId
     * @return
     */
    public String messagesTop(String publishId) {
        if (StringUtils.isEmpty(publishId)) {
            return null;
        }

        return this.messagesApi.messagesUpdateTop(publishId, 2) ? "操作成功" : null;
    }

    /**
     * 消息取消置顶
     *
     * @param publishId
     * @return
     */
    public String messagesUnTop(String publishId) {
        if (StringUtils.isEmpty(publishId)) {
            return null;
        }

        return this.messagesApi.messagesUpdateTop(publishId, 1) ? "操作成功" : null;
    }
}
